﻿using BCCommon;
using BCData.TMS.Agent.AgentCurrentlyProtocol;
using BCData.TMS.Agent.AgentCurrentlyProtocolAttachment;
using BCData.TMS.Agent.AgentRecord;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.Agent.AgentCurrentlyProtocol;
using BCDto.TMS.Agent.AgentCurrentlyProtocolAttachment;
using BCEntity.TMS.Agent.AgentCurrentlyProtocol;
using BCEntity.TMS.Agent.AgentCurrentlyProtocolAttachment;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCService.TMS.Agent.AgentCurrentlyProtocol
{
    public class AgentCurrentlyProtocolService : IAgentCurrentlyProtocolService
    {
        private readonly IAgentCurrentlyProtocolData agentCurrentlyProtocolData;
        private readonly IDatabaseContext databaseContext;
        private readonly IAgentRecordData agentRecordData;
        private readonly IAgentCurrentlyProtocolAttachmentData agentCurrentlyProtocolAttachmentData;

        public AgentCurrentlyProtocolService(IAgentCurrentlyProtocolData agentCurrentlyProtocolData,
            IDatabaseContext databaseContext,
            IAgentRecordData agentRecordData,
            IAgentCurrentlyProtocolAttachmentData agentCurrentlyProtocolAttachmentData)
        {
            this.agentCurrentlyProtocolData = agentCurrentlyProtocolData;
            this.databaseContext = databaseContext;
            this.agentRecordData = agentRecordData;
            this.agentCurrentlyProtocolAttachmentData = agentCurrentlyProtocolAttachmentData;
        }

        public AgentCurrentlyProtocolDto Add(AdminDto admin, long agentRecordId, AgentCurrentlyProtocolRequestDto requestDto)
        {
            var agentRecord = this.agentRecordData.GetEntity(agentRecordId).Result;
            if (agentRecord == null)
            {
                throw new ArgumentException("代理商信息不存在");
            }
            if (!requestDto.AgentCurrentlyProtocolAttachments.Any())
            {
                throw new ArgumentException("附件信息不能为空");
            }
            var result = this.agentCurrentlyProtocolData.GetEntityByAgentRecordId(agentRecordId).Result;
            if (result != null)
            {
                throw new ArgumentException("代理商现行协议信息已存在，不能重复添加");
            }
            databaseContext.BeginTransaction();
            result = this.agentCurrentlyProtocolData.Insert(new AgentCurrentlyProtocolEntity()
            {
                AgentRecordId = agentRecordId,
                ProtocolType = requestDto.ProtocolType,
                ProtocolContent = requestDto.ProtocolContent,
                SignDate = requestDto.SignDate,
                CreateTime = DateTime.Now
            }).GetAwaiter().GetResult();
            List<AgentCurrentlyProtocolAttachmentEntity> attachmentEntities = new List<AgentCurrentlyProtocolAttachmentEntity>();
            foreach(var item in requestDto.AgentCurrentlyProtocolAttachments)
            {
                attachmentEntities.Add(new AgentCurrentlyProtocolAttachmentEntity()
                {
                    AgentCurrentlyProtocolId = result.AgentCurrentlyProtocolId,
                    AttachmentAddress = item.AttachmentAddress,
                    AttachmentOrder = item.AttachmentOrder,
                    CreateTime = DateTime.Now
                });
            }
            this.agentCurrentlyProtocolAttachmentData.InsertAll(attachmentEntities).GetAwaiter().GetResult();
            databaseContext.Commit();
            return result.As<AgentCurrentlyProtocolDto>();
        }

        public void Delete(AdminDto admin, long agentCurrentlyProtocolId)
        {
            var result = this.agentCurrentlyProtocolData.GetEntity(agentCurrentlyProtocolId).Result;
            if (result == null)
            {
                throw new ArgumentException("代理商现行协议信息不存在");
            }
            databaseContext.BeginTransaction();
            this.agentCurrentlyProtocolData.Delete(agentCurrentlyProtocolId).GetAwaiter().GetResult();
            this.agentCurrentlyProtocolAttachmentData.Delete(agentCurrentlyProtocolId).GetAwaiter().GetResult();
            databaseContext.Commit();
        }

        public PageableList<AgentCurrentlyProtocolDto> Query(AdminDto admin, DateTime? signStartDate, DateTime? signEndDate, int pageIndex, int pageSize)
        {
            int? logonCmpanyId = admin.CompanyId;
            if (admin.Company.IsHeadOffice)
            {
                logonCmpanyId = null;
            }
            var (data, dataCount) = this.agentCurrentlyProtocolData.Query(logonCmpanyId, signStartDate, signEndDate, pageIndex, pageSize).Result;
            var list = data.As<List<AgentCurrentlyProtocolDto>>();
            var attachmentList = this.agentCurrentlyProtocolAttachmentData.GetListByIds(list.Select(p => p.AgentCurrentlyProtocolId).ToList()).Result;
            list.ForEach(p => p.AgentCurrentlyProtocolAttachments = attachmentList.Where(g => g.AgentCurrentlyProtocolId == p.AgentCurrentlyProtocolId).As<List<AgentCurrentlyProtocolAttachmentDto>>());
            return new PageableList<AgentCurrentlyProtocolDto>()
            {
                Count = dataCount,
                Items = list,
                PageIndex = pageIndex,
                PageSize = pageSize
            };
        }

        public AgentCurrentlyProtocolDto QuerySingle(long agentRecordId)
        {
            var result = this.agentCurrentlyProtocolData.GetEntityByAgentRecordId(agentRecordId).Result.As<AgentCurrentlyProtocolDto>();
            if (result == null)
            {
                throw new ArgumentException("代理商现行协议信息不存在");
            }
            result.AgentCurrentlyProtocolAttachments = this.agentCurrentlyProtocolAttachmentData.GetList(result.AgentCurrentlyProtocolId).Result.As<List<AgentCurrentlyProtocolAttachmentDto>>();
            return result;
        }

        public AgentCurrentlyProtocolDto Update(AdminDto admin, long agentCurrentlyProtocolId, AgentCurrentlyProtocolRequestDto requestDto)
        {
            var result = this.agentCurrentlyProtocolData.GetEntity(agentCurrentlyProtocolId).Result;
            if (result == null)
            {
                throw new ArgumentException("代理商现行协议信息不存在");
            }
            result.ProtocolType = requestDto.ProtocolType;
            result.ProtocolContent = requestDto.ProtocolContent;
            result.SignDate = requestDto.SignDate;
            result.CreateTime = DateTime.Now;
            databaseContext.BeginTransaction();
            this.agentCurrentlyProtocolData.Update(result).GetAwaiter().GetResult();
            this.agentCurrentlyProtocolAttachmentData.Delete(agentCurrentlyProtocolId).GetAwaiter().GetResult();
            List<AgentCurrentlyProtocolAttachmentEntity> attachmentEntities = new List<AgentCurrentlyProtocolAttachmentEntity>();
            foreach (var item in requestDto.AgentCurrentlyProtocolAttachments)
            {
                attachmentEntities.Add(new AgentCurrentlyProtocolAttachmentEntity()
                {
                    AgentCurrentlyProtocolId = result.AgentCurrentlyProtocolId,
                    AttachmentAddress = item.AttachmentAddress,
                    AttachmentOrder = item.AttachmentOrder,
                    CreateTime = DateTime.Now
                });
            }
            this.agentCurrentlyProtocolAttachmentData.InsertAll(attachmentEntities).GetAwaiter().GetResult();
            databaseContext.Commit();
            return result.As<AgentCurrentlyProtocolDto>();
        }
    }
}
